from machine import Pin
import onewire, ds18x20, time

leds = [
    Pin(16, Pin.OUT),  # LED1
    Pin(17, Pin.OUT),  # LED2
    Pin(18, Pin.OUT),  # LED3
    Pin(19, Pin.OUT),  # LED4
    Pin(12, Pin.OUT),  # LED5
    Pin(14, Pin.OUT),  # LED6
    Pin(27, Pin.OUT),  # LED7
    Pin(26, Pin.OUT)   # LED8
]
# 初始化DS18B20
ds18b20= ds18x20.DS18X20(onewire.OneWire(Pin(33,Pin.IN)))

if __name__ == "__main__":

    # 实始化
    roms = ds18b20.scan()  # 扫描DS18B20设备
    print("初始化成功DS18B20: ", roms)  # 打印找到的DS18B20设备

    while True:
        ds18b20.convert_temp()  # 启动温度转换
        time.sleep(1)  # 等待转换完成
        print("温度值: ", ds18b20.read_temp(roms[0]))  # 打印第一个DS18B20的温度值

        value = int(ds18b20.read_temp(roms[0])) # 读取第一个DS18B20的温度值
        for led in leds:  # 关闭所有LED
            led.value(0)
        
        if 29 <= value < 30:  # 根据温度值控制LED
            leds[0].value(1)  # LED1
        elif 31 <= value < 32:  # 根据温度值控制LED
            for led in range(2):
                leds[led].value(1)  # LED1\2
        elif 32 <= value < 33:  # 根据温度值控制LED
            for led in range(3):
                leds[led].value(1)  # LED1\2\3
        elif 33 <= value < 34:  # 根据温度值控制LED
            for led in range(4):
                leds[led].value(1)  # LED1\2\3\4
        elif 34 <= value < 35:  # 根据温度值控制LED
            for led in range(5):
                leds[led].value(1)  # LED1\2\3\4\5
        elif 35 <= value < 36:  # 根据温度值控制LED
            for led in range(6):
                leds[led].value(1)  # LED1\2\3\4\5\6
        elif 36 <= value < 37:  # 根据温度值控制LED
            for led in range(7):
                leds[led].value(1)  # LED1\2\3\4\5\6\7
        elif 37 <= value < 38:  # 根据温度值控制LED
            for led in range(8):
                leds[led].value(1)  # LED1\2\3\4\5\6\7\8
        elif 38<= value:  # 根据温度值控制LED
            for led in range(8):
                leds[led].value(1)  # LED1\2\3\4\5\6\7\8
            x = 0
            while x <= 8:  # 循环8次
                for i in range(8):
                    leds[i].value(1)  # 打开LED
                time.sleep(0.2)  # 延时0.2秒
                for i in range(8):
                    leds[i].value(0)  # 关闭LED
                time.sleep(0.2)  # 延时0.2秒
                x += 1  # x加1